/****************************************************************************
**
** Copyright (C) 2010 Tieto Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Tieto Corporation (info.ostrava@tieto.com)
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Tieto.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Tieto gives you certain additional
** rights.  These rights are described in the Tieto Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Tieto at info.ostrava@tieto.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtGui/QLabel>
#include <QtGui/QToolButton>
#include <QtGui/QAction>
#include <QtGui/QHBoxLayout>
#include <QtGui/QMessageBox>
#include <QtGui/QMenu>
#include <QtGui/QFileDialog>
#include <QtGui/QContextMenuEvent>
#include <QtGui/QPainter>
#include <QtGui/QSlider>
#include <QtGui/QSpinBox>
#include <QtGui/QPushButton>
#include <QtGui/QScrollArea> // TODO

#include <QDebug>

#include "areadetectionpage.h"
#include "areadetectionmodel.h"
#include "imageview.h"
#include "imagemodel.h"
#include "backgroundtaskwatcher.h"

AreaDetectionPage::AreaDetectionPage(AreaDetectionModel& model, QWidget *parent) :
    QWizardPage(parent), _model(model)
{
    setTitle(tr("Area detection"));
    setSubTitle(tr("Detects areas in provided image. "
                   "The detection is done by histogram-base method."));

    createActions();

    QPushButton *computeHistogramButton = new QPushButton;
    computeHistogramButton->setText(tr("Compute"));
    computeHistogramButton->setToolTip(tr("Compute histogram"));

    QPushButton *openButton = new QPushButton; // TODo
    openButton->setText(tr("Open"));    
    QObject::connect(computeHistogramButton, SIGNAL(clicked()), this, SLOT(computeHistogram()));
    QObject::connect(openButton, SIGNAL(clicked()), this, SLOT(openImage()));

    //sourceView = new ImageView();
    sourceView = new ImageView(AreaDetectionModel::ESourceImage);
    sourceView->setToolTip(tr("Source image"));    
    sourceView->setModel(&_model);

    QVBoxLayout *sourceLayout = new QVBoxLayout();    
    sourceLayout->addWidget(sourceView);
    sourceLayout->addWidget(computeHistogramButton);
    sourceLayout->addWidget(openButton);
    sourceLayout->setStretch(0,1);

    histogramView = new ImageView(AreaDetectionModel::EHistogramImageWithThreshold);
    histogramView->setToolTip("Histogram");
    histogramView->setModel(&_model);

    QSlider *histogramSlider = new QSlider(Qt::Horizontal);
    histogramSlider->setToolTip(tr("Threshold value"));
    histogramSlider->setRange(0, GRAYSCALE_COLOR_RANGE);

    QSpinBox *histogramSpinBox = new QSpinBox();
    histogramSpinBox->setToolTip(tr("Threshold value"));
    histogramSpinBox->setRange(0, GRAYSCALE_COLOR_RANGE);    

    QObject::connect(histogramSlider, SIGNAL(valueChanged(int)), histogramSpinBox, SLOT(setValue(int)));
    QObject::connect(histogramSpinBox, SIGNAL(valueChanged(int)), histogramSlider, SLOT(setValue(int)));
    QObject::connect(histogramSlider, SIGNAL(valueChanged(int)), &_model, SLOT(setThresholdValue(int)));
    QObject::connect(&_model, SIGNAL(thresholdValueChanged(int)), histogramSlider, SLOT(setValue(int)));   

    QHBoxLayout *sliderLayout = new QHBoxLayout;
    sliderLayout->addWidget(histogramSpinBox);
    sliderLayout->addWidget(histogramSlider);    

    QVBoxLayout *histogramLayout = new QVBoxLayout;
    histogramLayout->addWidget(histogramView);
    histogramLayout->addLayout(sliderLayout);
    histogramLayout->setStretch(0, 1);

    detectedAreasView = new ImageView(AreaDetectionModel::EDetectedAreasImage);
    detectedAreasView->setToolTip(tr("Detected areas"));
    detectedAreasView->setModel(&_model);

    QPushButton *detectButton = new QPushButton();
    detectButton->setText(tr("Detect"));
    detectButton->setToolTip(tr("Detect areas"));

    QObject::connect(detectButton, SIGNAL(clicked()), this, SLOT(detectAreas()));

    QVBoxLayout *areasLayout = new QVBoxLayout;
    areasLayout->addWidget(detectedAreasView);
    areasLayout->addWidget(detectButton);
    areasLayout->setStretch(0, 1);

    QHBoxLayout *detectAreasLayout = new QHBoxLayout;
    detectAreasLayout->addLayout(sourceLayout);
    detectAreasLayout->addLayout(histogramLayout);
    detectAreasLayout->addLayout(areasLayout);
    detectAreasLayout->setStretch(0, 1);
    detectAreasLayout->setStretch(1, 1);
    detectAreasLayout->setStretch(2, 1);

    QLabel *stepsLabel = new QLabel();
    stepsLabel->setText(tr("1. Compute histogram\n"
                           "2. Correct threshold value\n"
                           "3. Detect areas"));    
    stepsLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    stepsLabel->setWordWrap(true);

    QHBoxLayout *layout = new QHBoxLayout;    
    layout->addWidget(stepsLabel);
    layout->addLayout(detectAreasLayout);
    layout->setStretch(0, 1);
    layout->setStretch(1, 4);
    this->setLayout(layout);
}

void AreaDetectionPage::initializePage()
{
    //if (srcImage.isNull()) {
        QImage image;
        if (ImageModel::openImage(":/images/test.bmp", &image)) {
            GrayscaleImage sourceImage;
            sourceImage = ImageModel::convertImage(image).copy(); // MEM
            _model.setSourceImage(sourceImage);
        }
    //} // TODO
}

bool AreaDetectionPage::validatePage()
{
    if (_model.detectedAreasImage().isNull()) {
        if (_model.histogramImage().isNull()) {
            computeHistogram();
        }
        detectAreas();
    }
    return true;
}

void AreaDetectionPage::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    menu.addAction(openAct);
    menu.addAction(detectAct);
    menu.addAction(aboutAct);
    menu.exec(event->globalPos());
}

void AreaDetectionPage::computeHistogram()
{
    ComputeHistogramTask *task = _model.computeHistogram();
    BackgroundTaskWatcher watcher(task, tr("Compute histogram"));
    watcher.exec();
}

void AreaDetectionPage::openImage() // TODO optimalize
{
    qDebug() << "AreaDetectionPage::openImage";
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open source image"));
    QImage image;
    if (!fileName.isEmpty()) {
        if (ImageModel::openImage(fileName, &image)) {
            GrayscaleImage srcImage;
            srcImage = ImageModel::convertImage(image).copy();
            _model.setSourceImage(srcImage);
        }
    }
}

void AreaDetectionPage::detectAreas()
{       
    qDebug() << "AreaDetectionPage::detectAreas";
    AreaDetectionTask *task = _model.detectAreas();
    if (task) {
        BackgroundTaskWatcher watcher(task, tr("Compute histogram"));        
        watcher.exec();
// TODO        emit areasDetected(detectedAreasImage);
    }
}

void AreaDetectionPage::about()
{
    qDebug() << "AreaDetectionPage::about";
    QMessageBox::about(this, tr("Area detection"),
            tr("1. Open image.\n"
               "2. Correct threshold value in histogram.\n"
               "3. Detect areas."));
}

void AreaDetectionPage::createActions()
{
    openAct = new QAction(tr("&Open"), this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip(tr("Open an existing file"));
    QObject::connect(openAct, SIGNAL(triggered()), this, SLOT(openImage()));

    detectAct = new QAction(tr("&Detect"), this);
    detectAct->setShortcuts(QKeySequence::Print);
    detectAct->setStatusTip(tr("Detects areas in provided image"));
    QObject::connect(detectAct, SIGNAL(triggered()), this, SLOT(detectAreas()));

    aboutAct = new QAction(tr("&About"), this);
    aboutAct->setStatusTip(tr("Show the application's About box"));
    QObject::connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}

